//
//  XLUserSideNewPersonVC.m
//  XiangLove
//
//  Created by 李传坤 on 2018/6/4.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLUserSideNewPersonVC.h"
#import "XLNewHomeCell.h"
#import "MJRefresh.h"
#import "XLHTTPSessionManager.h"
#import "NewCamgirlModel.h"
#import <ReactiveCocoa.h>
#import "XLPersonPageViewController.h"
#import "XLAutoScrollView.h"
#import "XLTuijianBannnerListModel.h"
#import "XLWebViewController.h"
@interface XLUserSideNewPersonVC ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
    XLAutoScrollView *lunbView;//轮播
}
@property (nonatomic,strong)UICollectionView    *collectionView;
@property (nonatomic,strong)NSMutableArray      *modelArray;
@property (nonatomic,copy  )NSString            *page;
@property (nonatomic,strong)XLUserInfoModel     *userInfoModel;
@property (nonatomic,strong)NSMutableArray      *lunboArray;//轮播数组

//记录滑动
@property (nonatomic, assign) float contentOffset;
@property (nonatomic, assign) float oldOffset;


@end
@implementation XLUserSideNewPersonVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _page = @"1";
    [self addCollectionView];
    [self requrstTalkedPeoplePage:self.page];
    [self downloadBannerList];
    // Do any additional setup after loading the view.
}


- (void)downloadBannerList{
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"Api/v2/HomePage/GetBanners" parameters:@{@"type":@"0"} resultClass:[XLTuijianBannnerListModel class]]subscribeNext:^(id x) {
        if ([x isKindOfClass:[NSNull class]]) {
            return;
        }
        self.lunboArray =(NSMutableArray *)x;
        if (_lunboArray.count > 0) {
            if (lunbView == nil) {
                lunbView = [[XLAutoScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH/3)];
                [lunbView changeShowDict:_lunboArray
                               andBlocks:^(NSInteger shopTags) {
                                   if ( shopTags < _lunboArray.count ) {
                                       XLTuijianBannnerListModel *topM = _lunboArray[shopTags];
                                       [self WanNengPush:topM.Url];
                                   }
                               }];
            }
        }
    } error:^(NSError *error) {
        
    }];
}

/**
 *  跳转界面
 */
- (void)WanNengPush:(NSString *)VCName //后台给的vc名字
{
    if ([VCName rangeOfString:@"https://"].location != NSNotFound || [VCName rangeOfString:@"http://"].location != NSNotFound){  //网页链接
        XLWebViewController *vc = [[XLWebViewController alloc] init];
        vc.url = VCName;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        NSString *class = @"";//XLMyLevelViewController //XLTaskViewController
        if ([VCName rangeOfString:@"activity://"].location != NSNotFound){
            class = [[VCName componentsSeparatedByString:@"//"] lastObject];
        }
        const char *className = [class cStringUsingEncoding:NSASCIIStringEncoding];
        // 从一个字串返回一个类
        Class newClass = objc_getClass(className);
        if (!newClass)
        {   // 创建一个类
            Class superClass = [NSObject class];
            newClass = objc_allocateClassPair(superClass, className, 0);
            // 注册你创建的这个类
            objc_registerClassPair(newClass);
        }
        // 创建对象
        id instance = [[newClass alloc] init];
        NSDictionary *propertys = @{@"":@""};
        [propertys enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            // 检测这个对象是否存在该属性
            if ([self checkIsExistPropertyWithInstance:instance verifyPropertyName:key]) {
                // 利用kvc赋值
                [instance setValue:obj forKey:key];
                [self.navigationController pushViewController:instance animated:YES];
                
            }else{
                [MBProgressHUD showContent:@"敬请期待"];
            }
            
        }];
    }
}

/**
 *  检测对象是否存在该属性
 */
- (BOOL)checkIsExistPropertyWithInstance:(id)instance verifyPropertyName:(NSString *)verifyPropertyName
{
    unsigned int outCount, i;
    
    // 获取对象里的属性列表
    objc_property_t * properties = class_copyPropertyList([instance class], &outCount);
    
    for (i = 0; i < outCount; i++) {
        objc_property_t property =properties[i];
        //  属性名转成字符串
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        // 判断该属性是否存在
        if ([propertyName isEqualToString:verifyPropertyName]) {
            free(properties);
            return YES;
        }
    }
    free(properties);
    return NO;
}

#pragma mark --初始化 CollectionView
-(void)addCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 6;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    //flowLayout.headerReferenceSize = CGSizeMake(XQScreenW, 200);
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, XQScreenW, XQScreenH - 49) collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = kWhiteColor;
    [_collectionView registerClass:[XLNewHomeCell class] forCellWithReuseIdentifier:NSStringFromClass([XLNewHomeCell class])];
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderHost"];
    //[_collectionView registerClass:[XLUsersReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header"];

    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(handelGCHeaderTableView)];
    header.stateLabel.hidden = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    _collectionView.mj_header = header;
    _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(handelGCFootTableView)];
    [self.view addSubview:_collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 49, 0));
    }];
    
//    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
//    gradientLayer.colors = @[(id)RGBA(0, 0, 0, 0).CGColor, (id)RGBA(0, 0, 0, 0.5).CGColor];
//    gradientLayer.locations = @[@(0.5)];
//    gradientLayer.startPoint = CGPointMake(0.5, 1);
//    gradientLayer.endPoint = CGPointMake(0.5, 0);
//    gradientLayer.frame = CGRectMake(0, 0, ScreenWidth, 40);
//    [self.view.layer addSublayer:gradientLayer];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 下拉刷新
- (void)handelGCHeaderTableView {
    self.page = @"1";
    [self requrstTalkedPeoplePage:self.page];
    //[self reshOnlinePeoplesData];
    
}

#pragma mark - 上拉加载
- (void)handelGCFootTableView {
    self.page = [NSString stringWithFormat:@"%d", [self.page intValue] + 1];
    [self requrstTalkedPeoplePage:self.page];
}
- (void)requrstTalkedPeoplePage:(NSString *)page
{
    //    self.userInfoModel = [[XLAccountManager shareInstance] model];
    NSDictionary *dic = @{@"pageIndex":_page,
                          @"pageSize":@"16",
                          @"userId":[[XLAccountManager shareInstance]model].Id ,
                          @"type":@"2"};
    
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/api/v2/HomePage/GetHomePageList" parameters:dic resultClass:[NewCamgirlModel class]] subscribeNext:^(id x) {
        NSLog(@"美女列表==%@",x);
        [MBProgressHUD hideHUDForView:self.view];
        self.collectionView.hidden = NO;
        NSArray * listAry = x;
        if (![x isKindOfClass:[NSNull class]] && listAry.count > 0) {
            [self getJsonArray:listAry];
            [self.collectionView.mj_header endRefreshing];
            [self.collectionView.mj_footer endRefreshing];
        }else{
            [self.collectionView.mj_header endRefreshing];
            [self.collectionView.mj_footer endRefreshing];
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
    } error:^(NSError *error) {
        NSLog(@"%@", error);
        [MBProgressHUD hideHUDForView:self.view];
        
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
    }];
}
- (NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}
- (void)getJsonArray:(NSArray *)array {
    if ([array isKindOfClass:[NSNull class]] || array.count == 0 || array == nil) {
        
    } else {
        if ([self.page isEqualToString:@"1"]) {
            [self.modelArray removeAllObjects];
        } else {
            
        }
        [self.modelArray addObjectsFromArray:array];
    }
    [self.collectionView reloadData];
}

#pragma mark - CollectionDelegate
#pragma mark -- 返回每个item的高度
//每个item的纵向间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 8;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((XQScreenW-27)/2,((XQScreenW-25)/2)*200/174);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (_lunboArray.count == 0) {
        return CGSizeMake(XQScreenW,0);
    }
    return CGSizeMake(XQScreenW,(SCREEN_WIDTH-20) * 19 /71 + 18);
}

#pragma mark - CollectionHead
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableview = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        if (reusableview == nil) {
            reusableview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderHost" forIndexPath:indexPath];
        }
    }
    if (_lunboArray.count > 0) {
        [reusableview addSubview:lunbView];
    }
    
    return reusableview;
}

#pragma mark -- collectionView 的分组个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}


#pragma mark -- item 的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.modelArray.count;
    
}

#pragma mark -- cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NewCamgirlModel * model = self.modelArray[indexPath.row];
    XLNewHomeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([XLNewHomeCell class]) forIndexPath:indexPath];
    cell.dataModels = model;
    cell.videChatBtn.hostIndex = indexPath.row;
    cell.backgroundColor = XLThemeColor;
    return cell;
}
#pragma mark -- 选中某个cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NewCamgirlModel *model = self.modelArray[indexPath.row];
    //跳转私聊界面
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[NSStringFormat(@"%@",model.UserId)] succ:^(NSArray *friends) {
            for (TIMUserProfile *pro in friends)
            {
                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                dispatch_async(dispatch_get_main_queue(), ^{
                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                    //                    chat.isAnchor = model[@"IsAnchor"];
                    [self.navigationController pushViewController:chat animated:YES ];
                });
            }
        } fail:^(int code, NSString *msg) {
            NSLog(@"msg");
        }];
        return;
    }
    XLPersonPageViewController *vc = [[XLPersonPageViewController alloc] init];
    vc.userId = model.UserId;
    [self.navigationController pushViewController:vc animated:YES];
    
}


#pragma mark ----判断tableview上滑还是下滑
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.contentOffset = scrollView.contentOffset.y;
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat newOffsetY = scrollView.contentOffset.y;
    if (newOffsetY > self.oldOffset && self.oldOffset > self.contentOffset){//上滑
        //写上滑代码
        if(self.slideDistanceBlock)
        {
            self.slideDistanceBlock(NO);
        }
    }else if(newOffsetY < self.oldOffset && self.oldOffset < self.contentOffset){//下滑
        //写下滑代码
        if(self.slideDistanceBlock)
        {
            self.slideDistanceBlock(YES);
        }
    }
    self.oldOffset = scrollView.contentOffset.y;
}
//记录滑动结束时候的offset
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.oldOffset = scrollView.contentOffset.y;
}

-(NSMutableArray *)lunboArray
{
    if(_lunboArray == nil)
    {
        _lunboArray = [[NSMutableArray alloc]init];
    }
    return _lunboArray;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
